package com.zlq.cn.service.juhe;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlq.cn.config.OkhttpConfig;
import com.zlq.cn.entity.JuheZw;
import com.zlq.cn.entity.JuheZwContent;
import com.zlq.cn.mapper.juhe.JuheZwContentMapper;
import com.zlq.cn.mapper.juhe.JuheZwMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.Request;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 聚合作文 服务实现类
 * </p>
 *
 * @author zhoucl
 * @since 2023-12-13
 */
@Slf4j
@Service
public class JuheZwContentService extends ServiceImpl<JuheZwContentMapper, JuheZwContent> {

    public JuheZwContent content(JuheZwContent juheZwContent) {
        JuheZwContent dbJuheZwContent = super.getById(juheZwContent.getId());
        if (dbJuheZwContent == null) {
            try {
                Request request = new Request.Builder()
                        .url(HttpUrl.parse("http://zuowen.api.juhe.cn/zuowen/content").newBuilder()
                                .addQueryParameter("key", JuheZwService.KEY)
                                .addQueryParameter("id", juheZwContent.getId() + "")
                                .build())
                        .get()
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .build();
                String stringBody = OkhttpConfig.okHttpClient.newCall(request).execute().body().string();
                JSONObject body = JSON.parseObject(stringBody);
                Integer errorCode = body.getInteger("error_code");
                if (errorCode != null && errorCode == 0) {
                    JSONObject result = body.getJSONObject("result");
                    juheZwContent.setContent(result.getString("content"))
                            .setComment(result.getString("comment"))
                            .setSchool(result.getString("school"))
                            .setTeacher(result.getString("teacher"));
                    super.save(juheZwContent);
                } else {
                    throw new IllegalStateException(body.getString("reason"));
                }
            } catch (Exception e) {
                log.error("请求聚合作文详情失败", e);
                e.printStackTrace();
            }
            dbJuheZwContent = juheZwContent;
        }
        return dbJuheZwContent;
    }
}
